import requests #导入库
import os
import time

#接口请求地址
base_url = "https://cgate.zhaopin.com/campussxhcv2/pcJobFair/searchJobFair?x-zp-client-id=104c6138-fbc1-4855-b735-369ae5761d3f"
#请求头
headers_obj={
    "user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36"
}
#发起请求，配置headers的浏览器标识
#括号放入参数有请求地址和请求头
jsons_obj ={"jobFairName":"","pageIndex":1,"pageSize":40,"regionIds":[],"channel":"xiaoyuan","platform":"13","v":"0.61040606","version":"0.0.0"}
response = requests.post(base_url, headers=headers_obj, json=jsons_obj)

print(response.status_code)
json_data = response.json()
list_datas = json_data["data"]["result"]["list"]
for list_obj in list_datas:
    jobFairName = list_obj["jobFairName"]
    companyNum = list_obj["companyNum"]
    studentNum = list_obj["studentNum"]
    print(jobFairName,
          companyNum,
          studentNum
          )


# 创建保存图片的文件夹
image_folder = "jobfair_images"
if not os.path.exists(image_folder):
    os.makedirs(image_folder)


def download_image(image_url, job_fair_name):
    """下载图片并保存到本地"""
    if not image_url:
        return False
        
    try:
        # 处理可能的相对路径
        if image_url.startswith('//'):
            image_url = 'https:' + image_url
            
        # # 添加请求头，模拟浏览器
        # response = requests.get(image_url, headers=headers_obj, timeout=10)
        # response.raise_for_status()
        
        # 生成安全的文件名
        safe_name = "".join([c for c in job_fair_name if c.isalpha() or c.isdigit() or c in '._- '])
        file_ext = os.path.splitext(image_url)[1]
        if not file_ext:
            file_ext = '.jpg'  # 默认扩展名
            
        file_path = os.path.join(image_folder, f"{safe_name}{file_ext}")
        
        # 保存图片
        with open(file_path, 'wb') as f:
            f.write(response.content)
            
        print(f"图片已保存: {file_path}")
        return True
        
    except Exception as e:
        print(f"图片下载失败: {str(e)}")
        return False

try:
    # 发起请求
    response = requests.post(base_url, headers=headers_obj, json=jsons_obj)
    print(f"请求状态码: {response.status_code}")
    
    # 检查请求是否成功
    response.raise_for_status()
    
    # 解析JSON数据
    json_data = response.json()
    
    # 提取数据列表（增加了错误处理）
    if "data" in json_data and "result" in json_data["data"] and "list" in json_data["data"]["result"]:
        list_datas = json_data["data"]["result"]["list"]
        
        # 遍历数据并提取信息
        for idx, list_obj in enumerate(list_datas, 1):
            try:
                jobFairName = list_obj.get("jobFairName", "名称")
                companyNum = list_obj.get("companyNum", "企业数量")
                studentNum = list_obj.get("studentNum", "求职者数量")
                
                print(f"\n{idx}. 招聘会名称: {jobFairName}")
                print(f"   企业数量: {companyNum}")
                print(f"   学生数量: {studentNum}")
                
                # 尝试获取图片URL（这里假设图片字段为poster，你可能需要根据实际情况修改）
                image_url = list_obj.get("poster") or list_obj.get("logo") or list_obj.get("imageUrl")
                
                if image_url:
                    print(f"   图片URL: {image_url}")
                    download_image(image_url, f"{idx}_{jobFairName}")
                else:
                    print("   未找到图片URL")
                
                # 避免请求过于频繁
                time.sleep(1)
                
            except Exception as e:
                print(f"处理第{idx}条数据时出错: {str(e)}")
    else:
        print("数据结构不符合预期")
        print("完整响应数据:", json_data)

except requests.exceptions.HTTPError as e:
    print(f"HTTP请求错误: {e}")
    print("响应内容:", response.text)
except requests.exceptions.JSONDecodeError:
    print("无法解析JSON响应")
    print("响应内容:", response.text)
except Exception as e:
    print(f"发生错误: {e}")
